import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import { Table, Pagination, Grid, Button, MenuButton, Dialog, Message, Input, DatePicker } from '@alifd/next';
import IceContainer from '@icedesign/container';
import FoundationSymbol from '@icedesign/foundation-symbol';
import InspectionHistoryTableFilter from './InspectionHistoryTableFilter';
import { inspectionTypes } from "../../../../conf/inspectionTypeConfig";
import request from '../../../../instances/request';
const moment = require('moment');

const { Row, Col } = Grid;

export default class InspectionHistoryTable extends Component {
  static displayName = 'InspectionHistoryTable';

  static propTypes = {
    limit: PropTypes.number,
  };

  static defaultProps = {
    limit: 8,
  };

  constructor(props) {
    super(props);
    this.state = {
      __loading: true,
      currentPage: 1,
      inspectionList: [],
      total: 0,
      pageSize: this.props.limit,
      sStr: '',
      sType: '全部',
      sTime: null,
      inspectionTitle: '', // 待添加的巡视检查单标题
      createdAt: moment(), // 检查单归属日期
      tableWidth: 800,
    };
  }

  handlePaginationChange = (current) => {
    let { sStr, sType, sTime } = this.state;
    this.setState({
      currentPage: current,
    }, () => {
      this.fetchAndSetData({
        page: current,
        sStr,
        sType,
        sTime
      })
    });
  };

  renderType = (value, index, record) => {
    let name = '';
    inspectionTypes.forEach((ele, idx) => {
      if( ele.enName === record.type ) {
        name = ele.name;
      }
    });
    return <span style={{ display: 'block', width: '200px', whiteSpace: 'nowrap', overflow:'hidden', textOverflow: 'ellipsis' }}>{name}</span>;
  };

  renderSignatory = (value, index, record) => {
    if( record.type === 'it' || record.type === 'workstation' ) {
      let labels = [
        '周一白班-',
        '周一夜班-',
        '周二白班-',
        '周二夜班-',
        '周三白班-',
        '周三夜班-',
        '周四白班-',
        '周四夜班-',
        '周五白班-',
        '周五夜班-',
        '周六白班-',
        '周六夜班-',
        '周日白班-',
        '周日夜班-',
        '博维签名-',
      ];
      return (
        <div style={{ height: '40px', overflowY: 'auto' }} >
          {
            record.signatory.map((ele, idx) => {
              if( idx % 1 === 0) {
                return (
                  <tr key={idx} style={{ border: 'none', lineHeight: '20px' }}>
                    <td style={{ border: 'none', padding: '0 4px' }}>{labels[idx % labels.length]}{ele}</td>
                    {/*{*/}
                      {/*(idx + 1) !== 15 &&*/}
                      {/*<td style={{ border: 'none', padding: '0 4px' }}>{labels[(idx + 1) % labels.length]}{ele}</td>*/}
                    {/*}*/}
                  </tr>
                )
              }
            })
          }
        </div>
      )
    } else {  // 日检查单
      return (
        <div>
          {
            record.signatory.map((ele, idx) => {
              return (
                <div key={idx}>{['白班-', '夜班-', '博维-'][idx % 3]}{ele}</div>
              )
            })
          }
        </div>
      );
    }

  };

  handleAdd(type, typeName) {
    let dialog = Dialog.show({
      title: `添加${typeName}`,
      content: (
        <div>
          <div style={{ ...styles.formItem, width: '330px' }}>
            <div style={styles.formLabel}>检查单标题</div>
            <div style={{ marginLeft: '20px' }}>
              <Input placeholder="标题" onChange={(value) => {
                this.setState({
                  inspectionTitle: value,
                })
              }}/>
            </div>
          </div>
          <div style={{ ...styles.formItem, width: '330px' }}>
            <div style={styles.formLabel}>归属日期</div>
            <div style={{ marginLeft: '20px' }}>
              <DatePicker
                size="medium"
                defaultValue={this.state.createdAt}
                onChange={(value) => {
                  this.setState({
                    createdAt: value,
                  })
                }}
              />
            </div>
          </div>
        </div>
      ),
      onOk: () => {
        if(!this.state.inspectionTitle || !this.state.createdAt) {
          Message.warning('请输入巡视检查单标题和归属日期');
          return false;
        }
        Message.warning('巡视检查单创建时间可能较长，请耐心等待');
        return request.post('/inspectionList/add', {
          type,
          title: this.state.inspectionTitle,
          createdAt: this.state.createdAt.unix(),
        }).then((res) => {
          let { code, msg } = res.data;
          if(code !== 0 ) {
            Message.error(msg.error);
            return;
          }
          Message.success('创建成功');
          return this.fetchAndSetData({
            page: 1,
            sTime: this.state.sTime,
            sType: this.state.sType,
          }).then(() => {
            dialog.hide();
          });
        });
      },
      onCancel: () => {
        dialog.hide();
      }
    })
  }

  handleDelete(oid, e) {
    e.preventDefault();
    let dialog = Dialog.confirm({
      content: '您确认要删除此检查单吗？',
      onOk: () => {
        return request
          .post('/inspectionList/delete',{
            oid,
          })
          .then((res) => {
            let { code, msg } = res.data;
            if(code === 0) {
              Message.success('删除成功');
              this.fetchAndSetData({
                page: 1,
                sTime: this.state.sTime,
                sType: this.state.sType,
              }).then(() => {
                dialog.hide();
              });
            }
          });
      },
      onCancel: () => {
        dialog.hide();
      }
    })
  }

  renderOper = (value, index, record) => {
    let ftype;
    inspectionTypes.forEach((ele) => {
      if(ele.enName === record.type) {
        ftype = ele.ftype;
      }
    });
    let pathname = ftype === 'day' ?
      '/inspection/everyDay/inspectionRecord' :
      '/inspection/everyWeek/inspectionRecord';
    return (
      <div>
        <Link style={styles.link} to={{
          pathname: pathname,
          search: `?oid=${record.oid}&title=${record.title}&type=${record.type}`,
        }}>编辑</Link>
        <span style={styles.separator} />
        <span
          style={{ color: 'rgba(49, 128, 253, 0.65)', cursor: 'pointer' }}
          onClick={ this.handleDelete.bind(this, record.oid)}
        >
          删除
        </span>
      </div>
    );
  };

  async getInspectionList({ page = 1, limit = 8, sStr, sType, sTime }) {
    let res = await request
      .post('/inspectionList/list', {
        page,
        limit,
        sStr,
        sType,
        sTime,
      });
    let { code, msg } = res.data;
    return {
      code,
      inspectionList: msg.inspectionList,
      total: msg.total,
    }
  }

  async fetchAndSetData({ page = 1, limit = this.props.limit, sStr, sType, sTime }) {
    this.setState({
      __loading: true,
    });
    let { code, inspectionList, total } = await this.getInspectionList({
      page: page,
      limit: limit,
      sStr,
      sType,
      sTime,
    });
    this.setState({
      inspectionList: inspectionList,
      total: total,
      currentPage: page,
      __loading:false,
    })
  }

  handleSearch({ sStr, sTime, sType }) {
    let self = this;
    // todo: 如果self.setState写在这里就会导致无限刷新
    return function(e) {
      e.preventDefault();
      self.setState({
        sStr,
        sTime: sTime ? sTime.unix() : null,
        sType,
      }, () => {
        self.fetchAndSetData({
          sStr,
          sType,
          sTime: sTime ? sTime.unix() : null,
        });
      });
    }
  }

  propsConf = {
    className: 'next-myclass',
    style: { color: '#ff3000' },
  };

  setRowProps = (record, index) => {
    if (record.isAbnormal) {
      return this.propsConf;
    }
  };

  async componentDidMount() {
    this.setState({
      // todo: 下面表格的宽度必须大于这里的宽度才能够变成锁列
      // tableWidth: document.body.clientWidth - 290 - 25,
      // tableWidth: 400,
    });
    await this.fetchAndSetData({
      page: 1,
      sTime: this.state.sTime,
      sType: this.state.sType,
    });
  }

  render() {
    return (
      <IceContainer style={styles.container}>
        <Row>
          <Col>
            <div style={{ height: '60px', background: '#EAEBEF' }}>
              <div style={
                {
                  float: 'left',
                  fontSize: '20px',
                  fontWeight: 'bold',
                  height: '60px',
                  lineHeight: '60px',
                  paddingLeft: '30px',
                }
              }>
                <FoundationSymbol type='task' style={{ display: 'inline', verticalAlign: 'middle' }}/>
                <span >&nbsp;巡视检查单列表</span>
              </div>
              <div
                style={{
                  float: 'right',
                  height: '60px',
                  lineHeight: '60px',
                  paddingRight: '20px',
                }}
              >
                <MenuButton type='primary' popupTriggerType='hover' label='添加巡视检查单' size='medium' style={styles.menuButton}>
                  {
                    inspectionTypes.map((ele, idx) => {
                      return (
                        <MenuButton.Item key={idx} onClick={this.handleAdd.bind(this, ele.enName, ele.name)}>{ele.name}</MenuButton.Item>
                      )
                    })
                  }
                </MenuButton>
              </div>
            </div>
          </Col>
        </Row>
        <InspectionHistoryTableFilter  handleSearch={this.handleSearch.bind(this)}/>
        <div
          // style={{ width: this.state.tableWidth }}
        >
          <Table
            isZebra={true}
            loading={this.state.__loading}
            dataSource={this.state.inspectionList}
            className="basic-table"
            hasBorder={false}
            primaryKey="key"
            style={{ padding: '0 20px 20px' }}
            getRowProps={this.setRowProps.bind(this)}
          >
            <Table.Column
              title="编号"
              dataIndex="oid"
              width={120}
            />
            <Table.Column
              title="创建时间"
              dataIndex="createdTime"
              width={140}
              // lock
            />
            <Table.Column
              title="标题"
              width={200}
              cell={(value, index, record) => {
                let ftype;
                inspectionTypes.forEach((ele) => {
                  if(ele.enName === record.type) {
                    ftype = ele.ftype;
                  }
                });
                let pathname = ftype === 'day' ?
                  '/inspection/everyDay/inspectionRecord' :
                  '/inspection/everyWeek/inspectionRecord';

                return (
                  <Link style={styles.link} to={{
                    pathname: pathname,
                    search: `?oid=${record.oid}&title=${record.title}&type=${record.type}&createdTime=${record.createdTime}`,
                  }}><span style={{ display: 'block', whiteSpace: 'nowrap', overflow: 'hidden', width: '160px', textOverflow: 'ellipsis' }}>{record.title}</span></Link>
                )
              }}
            />
            <Table.Column
              title="类型"
              dataIndex="type"
              cell={this.renderType}
              width={250}
            />
            <Table.Column
              title="签字情况"
              dataIndex="signatory"
              cell={this.renderSignatory}
              // 为什么这里宽度不够的时候，白班签名和夜班签名会一样？
              width={200}
            />
            <Table.Column
              // lock='right'
              title="操作"
              dataIndex="oper"
              cell={this.renderOper}
              width={120}
            />
          </Table>
        </div>
        <Pagination
          style={styles.pagination}
          current={this.state.currentPage}
          total={this.state.total}
          pageSize={this.state.pageSize}
          onChange={this.handlePaginationChange}
        />
      </IceContainer>
    );
  }
}

const styles = {
  container: {
    padding: '0 0 20px 0',
  },
  link: {
    color: 'rgba(49, 128, 253, 0.65)',
    cursor: 'pointer',
    textDecoration: 'none',
  },
  separator: {
    margin: '0 4px',
    display: 'inline-block',
    height: '12px',
    width: '1px',
    verticalAlign: 'middle',
    background: '#e8e8e8',
  },
  pagination: {
    textAlign: 'right',
    marginRight: '20px',
  },
  menuButton: {
    width: '350px',
  },
  formItem: {
    display: 'flex',
    alignItems: 'center',
    margin: '10px 20px 40px 20px',
  },
  formLabel: {
    minWidth: '80px',
  },
};
